package com.anyou.mall.order.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.anyou.common.core.domain.ApiResult;
import com.anyou.common.core.domain.entity.SysUser;
import com.anyou.common.exception.ServiceException;
import com.anyou.common.exception.assertion.AnyouAssert;
import com.anyou.common.utils.DateUtils;
import com.anyou.common.utils.StringUtils;
import com.anyou.common.utils.TimeUtil;
import com.anyou.mall.dri.domain.Driver;
import com.anyou.mall.dri.mapper.DriverMapper;
import com.anyou.mall.fin.mapper.PlatformReconciliationMapper;
import com.anyou.mall.goo.goods.domain.GooGoods;
import com.anyou.mall.goo.goods.domain.GooGoodsVo;
import com.anyou.mall.goo.goods.domain.GoodsVo2;
import com.anyou.mall.goo.goods.domain.LiGoodsSku;
import com.anyou.mall.goo.goods.mapper.GooGoodsMapper;
import com.anyou.mall.goo.goods.mapper.LiGoodsSkuMapper;
import com.anyou.mall.goo.goodsSku.domain.GooGoodsSku;
import com.anyou.mall.goo.goodsSku.mapper.GooGoodsSkuMapper;
import com.anyou.mall.goo.goodsSpecs.domain.GooGoodsSpecs;
import com.anyou.mall.goo.goodsSpecs.mapper.GooGoodsSpecsMapper;
import com.anyou.mall.index.param.OrderNumParam;
import com.anyou.mall.index.vo.*;
import com.anyou.mall.order.domain.OrdOrder;
import com.anyou.mall.order.mapper.OrdOrderMapper;
import com.anyou.mall.order.orderGoods.domain.OrdOrderGoods;
import com.anyou.mall.order.orderGoods.mapper.OrdOrderGoodsMapper;
import com.anyou.mall.order.orderServe.domain.OrdOrderServe;
import com.anyou.mall.order.orderServe.mapper.OrdOrderServeMapper;
import com.anyou.mall.order.param.DeliveryParam;
import com.anyou.mall.order.param.DriverListParam;
import com.anyou.mall.order.service.IOrdOrderService;
import com.anyou.mall.order.vo.*;
import com.anyou.mall.platform.mapper.PlaPlatformSettingsMapper;
import com.anyou.mall.sho.domain.CarPartsShop;
import com.anyou.mall.sho.domain.CarPartsShopAudit;
import com.anyou.mall.sho.mapper.CarPartsShopAuditMapper;
import com.anyou.mall.sho.mapper.CarPartsShopMapper;
import com.anyou.mall.use.domain.User;
import com.anyou.mall.use.domain.UserNotice;
import com.anyou.mall.use.mapper.UserMapper;
import com.anyou.mall.use.mapper.UserNoticeMapper;
import com.anyou.mall.use.mapper.UserSystemNoticeMapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 订单Service业务层处理
 *
 * @author ruoyi
 * @date 2022-03-21
 */
@Service
@Slf4j
public class OrdOrderServiceImpl extends ServiceImpl<OrdOrderMapper, OrdOrder> implements IOrdOrderService
{
    @Autowired
    private OrdOrderMapper ordOrderMapper;

    @Autowired
    private OrdOrderGoodsMapper ordOrderGoodsMapper;

    @Autowired
    private GooGoodsMapper gooGoodsMapper;
    @Autowired
    private LiGoodsSkuMapper liGoodsSkuMapper;


    @Autowired
    private GooGoodsSkuMapper gooGoodsSkuMapper;
    @Autowired
    private GooGoodsSpecsMapper gooGoodsSpecsMapper;

    //汽配商审核
    @Autowired
    private CarPartsShopAuditMapper carPartsShopAuditMapper;

    @Autowired
    private CarPartsShopMapper carPartsShopMapper;



    @Autowired
    private OrdOrderServeMapper ordOrderServeMapper;

    @Autowired
    private PlaPlatformSettingsMapper plaPlatformSettingsMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private PlatformReconciliationMapper platformReconciliationMapper;



    @Autowired
    private UserNoticeMapper userNoticeMapper;
    @Autowired
    private DriverMapper driverMapper;

    @Autowired
    private UserSystemNoticeMapper userSystemNoticeMapper;

    /**
     * 查询订单
     *
     * @param orderId 订单主键
     * @return 订单
     */
    @Override
    public OrdOrder selectOrdOrderByOrderId(Long orderId)
    {

        OrdOrder ordOrder = ordOrderMapper.selectInfoById(orderId);
        AnyouAssert.notNull(ordOrder,"无效订单号！");

        //查询订单商品
        List<OrdOrderGoods> ordOrderGoods = ordOrderGoodsMapper.selectList(new LambdaQueryWrapper<OrdOrderGoods>()
                .eq(OrdOrderGoods::getOrderNo,ordOrder.getOrderNo()).eq(OrdOrderGoods::getDelFlag,0));
        ordOrderGoods.forEach(e->{
            LiGoodsSku liGoodsSku = liGoodsSkuMapper.selectById(e.getGoodsSkuId());
            if (liGoodsSku!=null){
                e.setSpecsCompose(liGoodsSku.getSimpleSpecs());
                //查询商品表的图片金额商品名
                GooGoods gooGoods = gooGoodsMapper.selectById(liGoodsSku.getGoodsId());
                if(gooGoods!=null){
                    e.setGoodsName(gooGoods.getGoodsName());
                    e.setGoodsImgUrl(gooGoods.getOriginal());
                }else{
                    e.setGoodsName("");
                    e.setGoodsImgUrl("");
                }

            }
        });

        //将订单商品赋值给订单
        ordOrder.setOrderGoodsList(ordOrderGoods);
        //查询购水用途
        List<OrderUseVo> useList=ordOrderMapper.selectOrderUseList(orderId);
        List<String> useList0 = useList.stream().map(OrderUseVo::getUseTitle).collect(Collectors.toList());
        String join = StringUtils.join(useList0, ",");
        ordOrder.setOrderUseList(join);
        //查询配送司机
        Driver driver = driverMapper.selectById(ordOrder.getDeliveryUserId());
        if(driver!=null){
            ordOrder.setDriverName(driver.getIndividualAuditName());
            ordOrder.setDriverPhone(driver.getIndividualAuditPhone());
            ordOrder.setDriverCar(driver.getAuditCarType());
        }
        return ordOrder;
    }

    /**
     * 查询订单列表
     *
     * @param ordOrder 订单
     * @return 订单
     */
    @Override
    public List<OrdOrder> selectOrdOrderList(OrdOrder ordOrder)
    {

        List<OrdOrder> getordOrders = ordOrderMapper.selectOrdOrderList(ordOrder);
        for(OrdOrder order : getordOrders){
            //查询购水用途
            List<OrderUseVo> useList=ordOrderMapper.selectOrderUseList(order.getOrderId());
            List<String> useList0 = useList.stream().map(OrderUseVo::getUseTitle).collect(Collectors.toList());
            String join = StringUtils.join(useList0, ",");
            order.setOrderUseList(join);
        }
        return getordOrders;
    }

    /**
     * 新增订单
     *
     * @param ordOrder 订单
     * @return 结果
     */
    @Override
    public int insertOrdOrder(OrdOrder ordOrder)
    {
        ordOrder.setCreateTime(DateUtils.getNowDate());
        return ordOrderMapper.insertOrdOrder(ordOrder);
    }

    /**
     * 修改订单
     *
     * @param ordOrder 订单
     * @return 结果
     */
    @Override
    public int updateOrdOrder(OrdOrder ordOrder)
    {
        ordOrder.setUpdateTime(DateUtils.getNowDate());
        return ordOrderMapper.updateOrdOrder(ordOrder);
    }

    /**
     * 批量删除订单
     *
     * @param orderIds 需要删除的订单主键
     * @return 结果
     */
    @Override
    public int deleteOrdOrderByOrderIds(Long[] orderIds)
    {
        return ordOrderMapper.deleteOrdOrderByOrderIds(orderIds);
    }

    /**
     * 删除订单信息
     *
     * @param orderId 订单主键
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteOrdOrderByOrderId(Long[] orderId)
    {
        for (Long id : orderId) {
            OrdOrder Order = ordOrderMapper.selectById(id);
            int i = ordOrderMapper.deleteById(id);

            LambdaQueryWrapper<OrdOrderGoods> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(OrdOrderGoods::getOrderNo,Order.getOrderNo());
            List<OrdOrderGoods> speSpecsValue = ordOrderGoodsMapper.selectList(queryWrapper);
            if(StringUtils.isNotEmpty(speSpecsValue)){
                speSpecsValue.forEach(e->{
                    ordOrderGoodsMapper.deleteById(e.getOrderGoodsId());
                });
            }
        }
        return 1;
    }

    @Override
    @Transactional
    public ApiResult orderDelivery(Long orderId, Long logisticsId,String logisticsName, String logisticsNo, String contactName, String contactPhone) {

        OrdOrder order = ordOrderMapper.selectById(orderId);
        if (order==null){
            ApiResult.success("订单不存在");
        }

        LambdaUpdateWrapper<OrdOrder> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.set(OrdOrder::getLogisticsId,logisticsName)//这里这个id字段存的是物流名称
                    .set(OrdOrder::getOrderStatus,3)
                    .set(OrdOrder::getLogisticsNo,logisticsNo)
                    .set(OrdOrder::getDeliverTime,new Date())//设置发货时间
                    .eq(OrdOrder::getOrderId,orderId);
            ordOrderMapper.update(null,updateWrapper);

        String content = "您的订单《"+order.getOrderNo()+"》已发货,请留意订单信息";
            // 用户系统消息添加
            this.addDeliveryNotice(order.getUserId(),content,order.getOrderId(),order.getOrderNo());

            // 发送短信
            //String resStr = SMSUtilOrderDeliver.sendSMS(order.getReceiverPhone(), order.getOrderNo());
            //if(!resStr.equals("success")){
            //    return ApiResult.error("发送短信失败！");
            //}
        return ApiResult.success();
    }

    /**
     * 用户系统消息添加
     *
     * @param userId  用户编号
     * @param content 消息内容
     * @param orderId 订单编号
     * @param orderNo 订单号
     */
    public  void  addDeliveryNotice(Long userId,String content,Long orderId,String orderNo){

        UserNotice userNotice = new UserNotice();
        userNotice.setSourceId(orderId);
        userNotice.setSide(3);
        userNotice.setContent(content);
        userNotice.setUserId(userId);
        userNotice.setNoticeType(1);
        userNoticeMapper.insert(userNotice);
    }

    @Override
    public ApiResult orderDetailed(String orderNo) {
        OrderDetailedVo orderDetailedVo = ordOrderMapper.OrderDetailed(orderNo);
        ShopInfoVo shopInfoVo = ordOrderMapper.shopSelect(orderNo);
        List<OrderGoodsListVo> orderGoodsListVo = ordOrderMapper.OrderGoodsListVo(orderNo);
        orderDetailedVo.setShopName(shopInfoVo.getShopName());
        orderDetailedVo.setOrderGoodsListVo(orderGoodsListVo);
        return ApiResult.success(orderDetailedVo);
    }

    @Override
    public List<DriverOrder> deliverOrderList(DriverOrder ordOrder) {
        List<DriverOrder> driverOrders = ordOrderMapper.deliverOrderList(ordOrder);

        return driverOrders;
    }

    @Override
    public DriverOrder deliverOrderInfo(Long orderId) {
        DriverOrder driverOrder = ordOrderMapper.deliverOrderInfo(orderId);
        AnyouAssert.notNull(driverOrder,"无效订单号！");

        //查询订单商品
        List<OrdOrderGoods> ordOrderGoods = ordOrderGoodsMapper.selectList(new LambdaQueryWrapper<OrdOrderGoods>()
                .eq(OrdOrderGoods::getOrderNo,driverOrder.getOrderNo()).eq(OrdOrderGoods::getDelFlag,0));
        ordOrderGoods.forEach(e->{
            LiGoodsSku liGoodsSku = liGoodsSkuMapper.selectById(e.getGoodsSkuId());
            if (liGoodsSku!=null){
                e.setSpecsCompose(liGoodsSku.getSimpleSpecs());
                //查询商品表的图片金额商品名
                GooGoods gooGoods = gooGoodsMapper.selectById(liGoodsSku.getGoodsId());
                if(gooGoods!=null){
                    e.setGoodsName(gooGoods.getGoodsName());
                    e.setGoodsImgUrl(gooGoods.getOriginal());
                }else{
                    e.setGoodsName("");
                    e.setGoodsImgUrl("");
                }

            }
        });

        //将订单商品赋值给订单
        driverOrder.setOrderGoodsList(ordOrderGoods);
        //查询购水用途
        List<OrderUseVo> useList=ordOrderMapper.selectOrderUseList(orderId);
        List<String> useList0 = useList.stream().map(OrderUseVo::getUseTitle).collect(Collectors.toList());
        String join = StringUtils.join(useList0, ",");
        driverOrder.setOrderUseList(join);

        return driverOrder;
    }

    @Override
    public void updateOrderWarn() {
        //超时48小时未完成送达的订单，或者超过要求时间未完成送达的订单，为预警订单
        //配送状态（0待揽件，1已揽件待入库，2已入库，3已出库待配送，4配送中，5已送达(完成)）
        List<OrdOrder> list = this.list(new QueryWrapper<OrdOrder>().lambda()
                .eq(OrdOrder::getDeliveryMode, "1")//收货类型（1配送到家，2到店领取）
                .eq(OrdOrder::getReceivingType, "1")//配送方式（1安邮配送，2商家配送，3物流）
                .ne(OrdOrder::getDistributionStatus,"5"));
        list.forEach(order->{
//            if(order.getAssignTime()!=null){
//                LocalDateTime now = LocalDateTime.now();
//                LocalDateTime assignTime = TimeUtil.dateToLocalDateTime(order.getAssignTime(), "yyyy-MM-dd HH:mm:ss");
//                //如果派单时间+48小时小于当前时间,为预警订单
//                if(assignTime.plusDays(2).isBefore(now)){
//                    order.setDeliveryWarn(1);
//                    this.updateById(order);
//                }
//                if(order.getRequiredDeliveryTime()!=null){
//                    LocalDateTime requiredDeliveryTime = TimeUtil.dateToLocalDateTime(order.getRequiredDeliveryTime(), "yyyy-MM-dd HH:mm:ss");
//                    //如果当前时间大于要求送达时间，预警订单
//                    if(now.isAfter(requiredDeliveryTime)){
//                        order.setDeliveryWarn(1);
//                        this.updateById(order);
//                    }
//                }
//            }

        });
    }

    @Override
    public void updateOrderIssue() {
        //超过24小时未完成的订单，为问题订单，（未完成揽件或者未完成送达)
        //配送状态（0待揽件，1已揽件待入库，2已入库，3已出库待配送，4配送中，5已送达(完成)）
        LocalDateTime now = LocalDateTime.now();
        //查询待揽件的订单
        List<OrdOrder> list = this.list(new QueryWrapper<OrdOrder>().lambda()
                .eq(OrdOrder::getDeliveryMode, "1")//收货类型（1配送到家，2到店领取）
                .eq(OrdOrder::getReceivingType, "1")//配送方式（1安邮配送，2商家配送，3物流）
                .eq(OrdOrder::getDistributionStatus,"0"));
        list.forEach(order->{
//            if(order.getAssignTime()!=null){
//                LocalDateTime assignTime = TimeUtil.dateToLocalDateTime(order.getAssignTime(), "yyyy-MM-dd HH:mm:ss");
//                if(assignTime.plusDays(1).isBefore(now)){
//                    //如果派单时间加24小时还小于当前时间，为问题订单
//                    order.setDeliveryIssue(1);
//                    this.updateById(order);
//                }
//            }

        });
        //查询已揽件待入库的订单
        List<OrdOrder> list3 = this.list(new QueryWrapper<OrdOrder>().lambda()
                .eq(OrdOrder::getDeliveryMode, "1")//收货类型（1配送到家，2到店领取）
                .eq(OrdOrder::getReceivingType, "1")//配送方式（1安邮配送，2商家配送，3物流）
                .eq(OrdOrder::getDistributionStatus,"1"));
        list3.forEach(order->{
//            if(order.getCollectTime()!=null){
//                LocalDateTime collectTime = TimeUtil.dateToLocalDateTime(order.getCollectTime(), "yyyy-MM-dd HH:mm:ss");
//                if(collectTime.plusDays(1).isBefore(now)){
//                    //如果揽件时间加24小时还小于当前时间，为问题订单
//                    order.setDeliveryIssue(1);
//                    this.updateById(order);
//                }
//            }

        });
        //查询未完成配送的订单
        List<OrdOrder> list2 = this.list(new QueryWrapper<OrdOrder>().lambda()
                .eq(OrdOrder::getDeliveryMode, "1")//收货类型（1配送到家，2到店领取）
                .eq(OrdOrder::getReceivingType, "1")//配送方式（1安邮配送，2商家配送，3物流）
                .in(OrdOrder::getDistributionStatus,"2","3","4"));
        list2.forEach(order->{
//            if(order.getInboundTime()!=null){
//                LocalDateTime inboundTime = TimeUtil.dateToLocalDateTime(order.getInboundTime(), "yyyy-MM-dd HH:mm:ss");
//                if(inboundTime.plusDays(1).isBefore(now)){
//                    order.setDeliveryIssue(1);
//                    this.updateById(order);
//                }
//            }
        });
    }

    @Override
    public void updateOrderIssueWarnToNo() {
        //配送状态（0待揽件，1已揽件待入库，2已入库，3已出库待配送，4配送中，5已送达(完成)）
        //查询已完成配送的订单
        List<OrdOrder> list = this.list(new QueryWrapper<OrdOrder>().lambda()
                .eq(OrdOrder::getDeliveryMode, "1")//收货类型（1配送到家，2到店领取）
                .eq(OrdOrder::getReceivingType, "1")//配送方式（1安邮配送，2商家配送，3物流）
                .eq(OrdOrder::getDistributionStatus,5));
        list.forEach(order->{
//            order.setDeliveryIssue(0);
//            order.setDeliveryWarn(0);
            this.updateById(order);
        });
    }

    @Override
    public ShopOrderMoneyVo getTotalMoney(Long carPartsShopId) {
        //查询总入账,总抽拥,总出账,总运费
        ShopOrderMoneyVo shopOrderMoney= platformReconciliationMapper.selectShopOrderMoneyVo(carPartsShopId);
        if (shopOrderMoney != null) {
            //计算总销售金额=总入账-总出账-总运费
            BigDecimal totalSellMoney=shopOrderMoney.getTotalInMoney().subtract(shopOrderMoney.getTotalOutMoney()).subtract(shopOrderMoney.getTotalYunMoney());
            shopOrderMoney.setTotalSellMoney(totalSellMoney);
            //订单总金额(总销售金额)-抽拥总金额=总收入
            BigDecimal totalMoney=totalSellMoney.subtract(shopOrderMoney.getTotalChouMoney());
            shopOrderMoney.setTotalMoney(totalMoney);
        }
        return shopOrderMoney;
    }

    /**
     * 查询总订单数量,待发货订单数量,待处理售后订单数量
     * @param carPartsShopId
     * @return
     */
    @Override
    public Card6Vo getTjOrderNum(Long carPartsShopId) {
        Card6Vo card6Vo = new Card6Vo();
        //总订单数
        Integer totalOrderNum = ordOrderMapper.selectCount(new LambdaQueryWrapper<OrdOrder>()
                .eq(OrdOrder::getDelFlag, 0));
        //待发货订单数
        Integer waitSendOrderNum = ordOrderMapper.selectCount(new LambdaQueryWrapper<OrdOrder>()
                .eq(OrdOrder::getDelFlag, 0)
                .eq(OrdOrder::getOrderStatus,"2"));

        //待处理售后订单数量
        Integer waitDoOrderNum = ordOrderServeMapper.selectCount(new LambdaQueryWrapper<OrdOrderServe>()
                .eq(OrdOrderServe::getDelFlag, "0")
                .eq(OrdOrderServe::getServeAuditStatus, "0"));
        card6Vo.setWaitSendOrderNum(waitSendOrderNum);
        card6Vo.setTotalOrderNum(totalOrderNum);
        card6Vo.setWaitDoOrderNum(waitDoOrderNum);
        return card6Vo;
    }

    @Override
    public ApiResult<List<OrderNumTjVo>> orderNumTj(OrderNumParam orderNumParam) {
        List<OrderNumTjVo> list=ordOrderMapper.orderNumTj(orderNumParam);
        return ApiResult.success(list);
    }

    @Override
    public SysUser selectUserById(Long userId) {
        SysUser user= ordOrderMapper.selectUserById(userId);
        return user;
    }

    @Override
    public List<OrderNumTjVo> getTotalMoney2(OrderNumParam orderNumParam) {
        List<OrderNumTjVo> list= ordOrderMapper.getTotalMoney2(orderNumParam);
        return list;
    }

    @Override
    public ApiResult<Card8Vo> card8Num() {
        Card8Vo card8Vo = new Card8Vo();
        //平台总收入,平台总销售金额,合伙人总数,总订单数,用户总数-----,（已提现金额，不活跃用户总数）
        //查询平台总收入,平台总销售金额
        MoneyVo moneyVo= this.getMoneyVo();
        card8Vo.setTotalMoney(moneyVo.getTotalMoney());
        card8Vo.setTotalSellMoney(moneyVo.getTotalSellMoney());
        //汽配商数量
        Integer shopNum = carPartsShopMapper.selectCount(new LambdaQueryWrapper<CarPartsShop>()
                .eq(CarPartsShop::getDelFlag, "0"));
        card8Vo.setShopNum(shopNum);

        //总订单数
        Integer orderNum = ordOrderMapper.selectCount(new LambdaQueryWrapper<OrdOrder>()
                .eq(OrdOrder::getDelFlag, "0"));
        card8Vo.setOrderNum(orderNum);

        //用户总数
        Integer userNum = userMapper.selectCount(new LambdaQueryWrapper<User>()
                .eq(User::getDelFlag, "0"));
        card8Vo.setUserNum(userNum);

        //7天前的日期
        LocalDate date7 = LocalDate.now().plusDays(-7);
        //不活跃用户总数
        String date = DateUtils.getStringByDate(date7);
        date=date+" 00:00:00";
        Integer noActiveUserNum = userMapper.selectNotActiveUserNum(date) ;
        card8Vo.setNoActUserNum(noActiveUserNum);

        //已提现总金额
        BigDecimal txMoney=ordOrderMapper.selectSumMoney();
        card8Vo.setTxMoney(txMoney);

        return ApiResult.success(card8Vo);
    }

    @Override
    public MoneyVo getMoneyVo() {
        MoneyVo moneyVo = new MoneyVo();

        ShopOrderMoneyVo shopOrderMoney = platformReconciliationMapper.selectShopOrderMoneyVo(null);
        if(shopOrderMoney!=null){
            //平台总销售额=所有商家销售额+平台团购商品销售额
            //商家销售额=总入账-总出账-运费
            BigDecimal totalSellMoney=shopOrderMoney.getTotalInMoney().subtract(shopOrderMoney.getTotalOutMoney()).subtract(shopOrderMoney.getTotalYunMoney());
            moneyVo.setTotalSellMoney(totalSellMoney);
            //平台总收入=总拥金+总运费+(团购订单总额-团购订单运费)
            BigDecimal totalMoney=shopOrderMoney.getTotalChouMoney().add(shopOrderMoney.getTotalYunMoney());
            moneyVo.setTotalMoney(totalMoney);
        }

        return moneyVo;
    }

    @Override
    public List<OrderNumTjVo> getPlatMoney(OrderNumParam orderNumParam) {
        List<OrderNumTjVo> orderNumTjVos = new ArrayList<>();
        List<ShopOrderMoneyVo> shopOrderMoneyVos = platformReconciliationMapper.selectShopOrderMoneyVo2(orderNumParam);
        shopOrderMoneyVos.forEach(shopOrderMoneyVo -> {
            //平台总收入=总拥金+总运费+(团购订单总额-团购订单运费)
            BigDecimal totalMoney=shopOrderMoneyVo.getTotalChouMoney().add(shopOrderMoneyVo.getTotalYunMoney());
            OrderNumTjVo orderNumTjVo = new OrderNumTjVo();
            orderNumTjVo.setDate(shopOrderMoneyVo.getDate());
            orderNumTjVo.setMoney(totalMoney);
            orderNumTjVos.add(orderNumTjVo);
        });
        return orderNumTjVos;
    }
    /**
     * 订单分析拆线走势图
     * @return
     */
    @Override
    public List<OrderNumTjVo2> getPlatMoney2(OrderNumParam orderNumParam) {
        List<OrderNumTjVo2> orderNumTjVos = new ArrayList<>();
        List<ShopOrderMoneyVo> shopOrderMoneyVos = platformReconciliationMapper.selectShopOrderMoneyVo3(orderNumParam);
        shopOrderMoneyVos.forEach(shopOrderMoneyVo -> {
            //平台总收入=总拥金+总运费+(团购订单总额-团购订单运费)
            BigDecimal totalMoney=shopOrderMoneyVo.getTotalChouMoney().add(shopOrderMoneyVo.getTotalYunMoney());
            OrderNumTjVo2 orderNumTjVo = new OrderNumTjVo2();
            orderNumTjVo.setDate(shopOrderMoneyVo.getDate());
            orderNumTjVo.setMoney(totalMoney);
            orderNumTjVo.setOrderNum(shopOrderMoneyVo.getOrderNum());
            orderNumTjVos.add(orderNumTjVo);
        });
        return orderNumTjVos;
    }

    @Override
    public String importData(List<OrdOrder> orderList, boolean updateSupport, String operName) {
        if (StringUtils.isNull(orderList) || orderList.size() == 0)
        {
            throw new ServiceException("导入数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        //for (OrdOrder order : orderList)
        //{
        //    try
        //    {
        //        // 验证是否存在这个订单
        //        SysUser u = userMapper.selectUserByUserName(user.getUserName());
        //        if (StringUtils.isNull(u))
        //        {
        //            BeanValidators.validateWithException(validator, user);
        //            user.setPassword(SecurityUtils.encryptPassword(password));
        //            user.setCreateBy(operName);
        //            this.insertUser(user);
        //            successNum++;
        //            successMsg.append("<br/>" + successNum + "、账号 " + user.getUserName() + " 导入成功");
        //        }
        //        else if (isUpdateSupport)
        //        {
        //            BeanValidators.validateWithException(validator, user);
        //            user.setUpdateBy(operName);
        //            this.updateUser(user);
        //            successNum++;
        //            successMsg.append("<br/>" + successNum + "、账号 " + user.getUserName() + " 更新成功");
        //        }
        //        else
        //        {
        //            failureNum++;
        //            failureMsg.append("<br/>" + failureNum + "、账号 " + user.getUserName() + " 已存在");
        //        }
        //    }
        //    catch (Exception e)
        //    {
        //        failureNum++;
        //        String msg = "<br/>" + failureNum + "、账号 " + user.getUserName() + " 导入失败：";
        //        failureMsg.append(msg + e.getMessage());
        //        log.error(msg, e);
        //    }
        //}
        //if (failureNum > 0)
        //{
        //    failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
        //    throw new ServiceException(failureMsg.toString());
        //}
        //else
        //{
        //    successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        //}
        return successMsg.toString();
    }

    @Override
    public List<OrdOrder> selectIntegralOrderList(OrdOrder ordOrder) {
        List<OrdOrder> getordOrders = ordOrderMapper.selectIntegralOrderList(ordOrder);
        return getordOrders;
    }

    @Override
    public OrdOrder selectIntegralOrderByOrderId(Long orderId) {
        OrdOrder ordOrder = ordOrderMapper.selectById(orderId);
        AnyouAssert.notNull(ordOrder,"无效订单号！");
        //获取用户手机号
        if (log.isDebugEnabled()){
            log.debug("【订单详情】获取到当前用户id为【{}】",ordOrder.getUserId());
        }
        AnyouAssert.notNull(ordOrder.getUserId(),"用户信息异常！");
        User user = userMapper.selectUserByUserId(ordOrder.getUserId());
        AnyouAssert.notNull(user,"用户信息异常！");
        ordOrder.setPhoneNumber(user.getPhoneNumber());

        //查询积分订单商品
        GooGoodsVo gooGoodsVo=getGoods(ordOrder.getJfGoodsId());
        ordOrder.setGoods(gooGoodsVo);
        return ordOrder;
    }

    private GooGoodsVo getGoods(Long jfGoodsId) {
        GooGoods goods = gooGoodsMapper.selectOne(new LambdaQueryWrapper<GooGoods>()
                .eq(GooGoods::getGoodsId,jfGoodsId).eq(GooGoods::getDelFlag,0));
        if(goods==null){
            throw new ServiceException("商品数据不存在！");
        }
        GooGoodsVo gooGoodsVo = new GooGoodsVo();
        BeanUtils.copyProperties(goods,gooGoodsVo);
        return gooGoodsVo;
    }

    /**
     * 水票订单列表
     * @param ordOrder
     * @return
     */
    @Override
    public List<OrdOrder> selectWaterCouponOrderList(OrdOrder ordOrder) {
        List<OrdOrder> ordOrders = ordOrderMapper.selectWaterCouponOrderList(ordOrder);
        ordOrders.forEach(e->{
            //查询规格
            List<OrdOrderGoods> ordOrderGoods = ordOrderGoodsMapper.selectList(
                    new LambdaQueryWrapper<OrdOrderGoods>().eq(OrdOrderGoods::getOrderNo, e.getOrderNo()));
            if(CollUtil.isNotEmpty(ordOrderGoods)){
                Long goodsSkuId = ordOrderGoods.get(0).getGoodsSkuId();
                LiGoodsSku liGoodsSku = liGoodsSkuMapper.selectById(goodsSkuId);
                e.setWaterSpec(liGoodsSku.getSimpleSpecs());
            }

        });
        return ordOrders;
    }
    /**
     * 通过商品查规格列表
     * @param goodsId
     * @return
     */
    @Override
    public List<LiGoodsSku> specsListByGoodsId(Long goodsId) {
        List<LiGoodsSku> gooGoodsSkus = liGoodsSkuMapper.selectList(
                new LambdaQueryWrapper<LiGoodsSku>()
                .eq(LiGoodsSku::getGoodsId, goodsId));
        return gooGoodsSkus;
    }
    /**
     * 分配/改派司机
     * @param parm
     */
    @Override
    public void distrDeliveryDriver(DeliveryParam parm) {
        //查询司机
        List<Driver> drivers = driverMapper.selectList(new LambdaQueryWrapper<Driver>()
                .eq(Driver::getUserType, 0));
        if(parm.getType()==1&&parm.getMothed()==1){
            if(CollUtil.isEmpty(drivers)){
                throw new ServiceException("没有任何司机，所以无法随机分配司机！");
            }
        }
        if(!parm.getOrderIds().isEmpty()){
           parm.getOrderIds().forEach(orderId->{
                OrdOrder ordOrder = this.getById(orderId);
                if(parm.getType()==1&&parm.getMothed()==1){
                    //随机分配司机
                    Driver driver = drivers.get(new Random().nextInt(drivers.size()));
                    ordOrder.setDeliveryUserId(driver.getDriverId());
                }else{
                    ordOrder.setDeliveryUserId(parm.getDriverId());
                }

                if(parm.getIsUrgentDelivery()!=null){
                    ordOrder.setIsUrgentDelivery(parm.getIsUrgentDelivery().toString());
                }
                ordOrder.setDistributionStatus(2);
                ordOrder.setAssignTime(new Date());//派单时间
                this.updateById( ordOrder);
                //为司机新增消息

            });
        }

    }

    @Override
    public List<DriverListVo> driverList(DriverListParam param) {
        List<DriverListVo> list=ordOrderMapper.driverList(param);
        return list;
    }

    /**
     * 商品列表
     * @param goodsName
     * @return
     */
    @Override
    public List<GoodsVo2> goodsListByGoodsName(String goodsName) {
        List<GoodsVo2> list=ordOrderMapper.goodsList(goodsName);
        return list;
    }


}
